﻿using System;
using System.Windows.Forms;
using System.Linq;
using Cubicle.Nuget.Core;
using Cubicle.Nuget.Functions;

namespace Cubicle.Nuget.Gui
{
    public partial class FeedManagerUserControl : UserControl
    {
        public FeedManagerUserControl()
        {
            InitializeComponent();
            RefreshClients();
        }

        private NugetClient SelectedClient
        {
            get
            {
                if (FeedGridView.SelectedRows.Count == 0 || NugetFunctions.FeedManager == null) return null;
                var name = FeedGridView.SelectedRows[0].Cells["Name"].Value.ToString();
                return NugetFunctions.FeedManager[name];
            }
        }

        private void RefreshClients()
        {
            if (NugetFunctions.FeedManager == null) return;
            FeedGridView.AutoGenerateColumns = true;
            FeedGridView.DataSource = NugetFunctions.FeedManager.Select(c =>
                new {
                    Name = c.Name,
                    Default = c.IsDefault,
                    Uri = c.Uri
                })
                .ToList();
            FeedGridView.Refresh();
        }

        private void makeDefaultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SelectedClient == null) return;
            NugetFunctions.FeedManager.SetDefault(SelectedClient.Name);
            RefreshClients();
        }

        private void removeFeedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SelectedClient == null) return;
            NugetFunctions.FeedManager.RemoveFeed(SelectedClient.Name);
            RefreshClients();
        }

        private void FeedGridView_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            var name = e.Row.Cells["Name"].Value.ToString();
            NugetFunctions.FeedManager.RemoveFeed(name);
        }

        private void FeedGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            var name = e.Row.Cells["Name"].Value.ToString();
            var uri = e.Row.Cells["Uri"].Value.ToString();
            var isDefault = (bool)e.Row.Cells["Default"].Value;
            NugetFunctions.FeedManager.AddFeed(name, isDefault, uri);
        }
    }
}
